import { type FC } from 'react';
import { useSafeState, useMemoizedFn } from 'ahooks';
import { View, TextInput, StyleSheet } from 'react-native';
import { grayColor } from '@/constants/Colors';
import type { InputProps } from './types';
import styles from './styles';

const Input: FC<InputProps> = (props) => {
  const { password, prefix, suffix } = props;
  const [focus, setFocus] = useSafeState(false);
  const [active, setActive] = useSafeState(false);
  const _disabled_ = props.readOnly || props.disabled; 
  const _focus_ = !!(focus || active || props.active);

  const onFocus = useMemoizedFn(() => {
    setFocus(true);
  });

  const onBlur = useMemoizedFn(() => {
    setFocus(false);
  });

  const onPressIn = useMemoizedFn(() => {
    setActive(true);
  });

  const onPressOut = useMemoizedFn(() => {
    setActive(false);
  });

  const renderPrefix = () => {
    if (!prefix) return null;
    return (
      <View style={styles.prefix}>
        {prefix(_focus_)}
      </View>
    );
  }

  const renderSuffix = () => {
    if (!suffix) return null;
    return (
      <View style={styles.suffix}>
        {suffix(_focus_)}
      </View>
    );
  }

  return (
    <View style={
      StyleSheet.flatten([
        styles.container,
        _focus_ && styles.focus
      ])}
    >
      {renderPrefix()}
      <TextInput
        onBlur={onBlur}
        onFocus={onFocus}
        value={props.value}
        style={styles.input}
        onPressIn={onPressIn}
        onPressOut={onPressOut}
        readOnly={_disabled_}
        secureTextEntry={password}
        autoFocus={props.autoFocus}
        onChangeText={props.onChange}
        placeholderTextColor={grayColor}
        placeholder={props.placeholder}
      />
      {renderSuffix()}
    </View>
  );
}

export default Input;